package ace.module.account.core.impl.service.callback.auth.impl;

import ace.module.account.core.impl.manager.IamApplicationOauth2ClientManager;
import ace.module.account.core.impl.service.callback.auth.Oauth2AuthenticationCallbackService;
import ace.module.account.core.impl.service.callback.auth.handler.Oauth2AuthenticationCallbackHandlerManager;
import ace.module.account.core.impl.service.callback.auth.model.bo.Oauth2AuthenticationCallbackContext;
import ace.module.account.oauth2.api.model.input.IamOauth2CallbackAuthenticationInput;
import ace.module.oauth2.server.api.callback.model.input.Oauth2AceAuthenticationCallbackInput;
import ace.module.oauth2.server.api.model.dto.ext.Oauth2AceAuthResultDto;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * @author caspar
 * @date 2023/3/16 9:27
 */
@AllArgsConstructor
@Component
public class Oauth2AuthenticationCallbackServiceImpl
    implements Oauth2AuthenticationCallbackService {

  private final Oauth2AuthenticationCallbackHandlerManager oauth2AuthenticationCallbackHandlerManager;
  private final IamApplicationOauth2ClientManager iamApplicationOauth2ClientManager;

  @Override
  public Oauth2AceAuthResultDto authentication(IamOauth2CallbackAuthenticationInput input) {
    Oauth2AuthenticationCallbackContext context = Oauth2AuthenticationCallbackContext
        .builder()
        .bodyModel(input)
        .build();

    return oauth2AuthenticationCallbackHandlerManager.authentication(context);
  }

  @Override
  public Oauth2AceAuthResultDto authenticationByConfig(Oauth2AceAuthenticationCallbackInput input) {
    Long iamAppId = iamApplicationOauth2ClientManager.getAndCheckNotNullByIdOfClientIdAndDeleteFlagIsFalse(input.getIdOfClient()).getIamAppId();

    IamOauth2CallbackAuthenticationInput iamOauth2CallbackAuthenticationInput = IamOauth2CallbackAuthenticationInput.builder()
        .accountTag(StringUtils.EMPTY)
        .iamAppId(iamAppId)
        .oauth2AuthenticationCallbackInput(input)
        .build();

    Oauth2AuthenticationCallbackContext context = Oauth2AuthenticationCallbackContext
        .builder()
        .bodyModel(iamOauth2CallbackAuthenticationInput)
        .build();

    return oauth2AuthenticationCallbackHandlerManager.authentication(context);
  }
}
